# -*- coding: utf-8 -*-

# backend/models/websocket_event.py
from sqlalchemy import Column, String, Text, DateTime, Integer, Boolean, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.postgresql import JSON
from datetime import datetime

from backend.core.database import Base


class WebSocketEvent(Base):
    """WebSocket事件记录"""
    
    __tablename__ = "websocket_events"
    
    id = Column(String, primary_key=True)
    user_id = Column(String, ForeignKey("users.id"), nullable=False)
    project_id = Column(String, ForeignKey("projects.id"), nullable=True)
    connection_id = Column(String, nullable=False)
    event_type = Column(String, nullable=False)
    event_data = Column(JSON, nullable=True)
    timestamp = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    # 关系
    user = relationship("User", back_populates="websocket_events")
    project = relationship("Project", back_populates="websocket_events")


class WebSocketConnection(Base):
    """WebSocket连接记录"""
    
    __tablename__ = "websocket_connections"
    
    id = Column(String, primary_key=True)
    user_id = Column(String, ForeignKey("users.id"), nullable=False)
    project_id = Column(String, ForeignKey("projects.id"), nullable=True)
    connection_id = Column(String, unique=True, nullable=False)
    ip_address = Column(String, nullable=True)
    user_agent = Column(String, nullable=True)
    connected_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    disconnected_at = Column(DateTime, nullable=True)
    is_active = Column(Boolean, default=True, nullable=False)
    last_ping = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    # 关系
    user = relationship("User", back_populates="websocket_connections")
    project = relationship("Project", back_populates="websocket_connections")
